package dormouse.bookmarks.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.List;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import dormouse.bookmarks.AbstractBookmarkReader;
import dormouse.bookmarks.Bookmark;
import dormouse.bookmarks.IBookmarkReader;

/**
 * Implements Linux bookmark files which are in the following format:
 * 
 * <code>
 * [Desktop Entry]
 * Version=1.0
 * Encoding=UTF-8
 * Name=Link to From Java Platform Improvements to Better Teaching: A Conversation With Java Champion Cay Horstmann
 * Type=Link
 * URL=http://java.sun.com/developer/technicalArticles/Interviews/community/horstmann_qa.html
 * Icon=gnome-fs-bookmark
 * 
 * </code>
 */
public class LinuxBookmarkReader extends AbstractBookmarkReader implements IBookmarkReader {

    
    private static final int LINE_NAME = 3;
    private static final int LINE_URL = 5;
    
    @Override
    public Bookmark readBookmark(String urlStr) throws IOException {
        Bookmark bookmark = new Bookmark();

        try {
            
            FileSystemManager manager = VFS.getManager();
            FileObject file = manager.resolveFile(urlStr);

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(file.getContent().getInputStream()));
            String str;
            int count = 0;
            String[] line = null;
            
            while ((str = in.readLine()) != null) {
                
                switch (count){
                    case LINE_NAME: {
                        line = str.split("=");
                        bookmark.setName(line[1]);
                        break;
                    }
                    case LINE_URL:{
                        line = str.split("=");
                        bookmark.setUrl(line[1]);
                        break;
                    }
                }
                
                count++;
            }
            in.close();
        } catch (MalformedURLException e) {
            throw new IOException(e.getMessage());
        }


        return bookmark;
    }

    @Override
    public List<Bookmark> readBookmarks(String folderUrl) throws IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
